//
//  SearchResultDetailViewController.m
//  BVCMS Search
//
//  Created by Allen Thomas on 9/13/10.
//

#import "SearchResultDetailViewController.h"
#import "ImageViewController.h"
#import "SearchFormViewController.h"
#import "BVCMSAppDelegate.h"
#import "PersonDetails.h"

@implementation SearchResultDetailViewController

#define SearchFormView [[self.navigationController viewControllers] objectAtIndex:0]

@synthesize person;
@synthesize table, headerView;
@synthesize photo, nameLabel, statusLabel, imageLoad;


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	UIImage *background = [UIImage imageNamed: @"background.png"];    
	UIImageView *imageView = [[UIImageView alloc] initWithImage: background]; 
	
	[self.view addSubview: imageView];
	[self.view sendSubviewToBack: imageView];
	[imageView release];
	
	table.backgroundColor = [UIColor clearColor];
	
	table.tableHeaderView = headerView;
	
	//set photo image to curved corners
	CALayer *layer = [photo layer];
	[layer setMasksToBounds:YES];
	[layer setCornerRadius:10.0];
	[layer setBorderColor:[[UIColor darkGrayColor] CGColor]];
	[layer setBorderWidth:1.5];
	
	//set labels
	NSString *fullName = [NSString stringWithFormat:@"%@ %@", [person.details valueForKey:@"first"], [person.details valueForKey:@"last"] ];
	nameLabel.text = fullName;
	statusLabel.text = [person.details valueForKey:@"memberstatus"];
	
	isImageLoaded = NO;
	
	if( [[person.details valueForKey:@"haspicture"] isEqualToString:@"1"] ) {
		[self downloadPhoto];
	}
	
    [super viewDidLoad];
}

#pragma mark Table Methods

/*
 Triggered when the user selects a row.  In this case, we get the row type, and then do the specific action.
 */
- (NSIndexPath *)tableView:(UITableView *)tableView
  willSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
	if (indexPath.section == 0 ) {
		if(indexPath.row == 0) {
			UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
			UITableViewCell *othercell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
			
			NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@,%@", cell.detailTextLabel.text,othercell.detailTextLabel.text];
			urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString: urlString]];
		}
	}
	
	if (indexPath.section == 1 ) {
			
		if (indexPath.row >= 0 && indexPath.row < 3) {
			UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

			NSString *trimmedPhoneNumber = [[cell.detailTextLabel.text componentsSeparatedByCharactersInSet:
											[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
											componentsJoinedByString:@""];
			NSString *urlString = [NSString stringWithFormat:@"tel://%@", trimmedPhoneNumber];
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
		}
		if(indexPath.row == 3) {
			UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

			NSString *urlString = [NSString stringWithFormat:@"mailto:%@", cell.detailTextLabel.text];
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
		}
		
	}
	
	if( indexPath.section == 2 || indexPath.section == 3 ) {
		NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"LoadingView" owner:self options:nil];
		
		if(loadingView) {
			[self.view bringSubviewToFront:loadingView];
		} else {
			loadingView = [nibObjects objectAtIndex:0];
			loadingView.center = CGPointMake(160, 160);
			[self.view addSubview:loadingView];
		}		
		
		[tableView deselectRowAtIndexPath:indexPath animated:YES];
		
		connection = [[PersonDetailsConnection alloc] init];
		connection.delegate = self;
		if( [person.familyMembers count] > 0 && indexPath.section == 2)
			connection.personId = [[person.familyMembers objectAtIndex:indexPath.row] valueForKey:@"peopleid"];
		else 
			connection.personId = [[person.relatives objectAtIndex:indexPath.row] valueForKey:@"hohid"];
		[connection startDownload];
		
	}
	
	return nil;
}

/*
 Return number of sections.
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    int additionalSections = 0;
	if( [person.relatives count] > 0 ) 
		additionalSections++;
	if( [person.familyMembers count] > 0 ) 
		additionalSections++;
	return 2 + additionalSections;
}

/*
 Return the title of a section.
 */
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
	switch (section) {
		case 0:
			return @"General Info";
			break;
		case 1:
			return @"Contact Info";
			break;
	}
	
	if( section == 2 && [person.familyMembers count] > 0 ) 
		return @"Family Members";
	else 
		return @"Relatives";
	
	return 0;
}

/*
 Return number of rows in a section.
 */
- (NSInteger)tableView:(UITableView *)table
 numberOfRowsInSection:(NSInteger)section {
	switch (section) {
		case 0:
			return 3;
			break;
		case 1:
			return 4;
			break;
	}
	
	if( section == 2 && [person.familyMembers count] > 0 ) 
		return [person.familyMembers count];
	else 
		return [person.relatives count];
	
	return 0;
}

/*
 Return a UITableViewCell for a row.  Some rows will have different accessory indicators.
 */
- (UITableViewCell *)tableView:(UITableView *)tableView
		 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
	
	
	UITableViewCell * cell = [tableView
							  dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
	
	if(cell == nil) {
		cell = [[[UITableViewCell alloc]
				initWithStyle:UITableViewCellStyleValue1
				reuseIdentifier:SimpleTableIdentifier] autorelease];
		
	}
	
	cell.textLabel.font = [UIFont boldSystemFontOfSize:12.0];
	cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:13.0];
	cell.detailTextLabel.minimumFontSize = 10;
	cell.accessoryType = UITableViewCellAccessoryNone;
	cell.accessoryView = nil;
	
	switch (indexPath.section) {
		case 0:
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			
			switch (indexPath.row) {
				case 0:
					cell.textLabel.text = @"Address";
					cell.textLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
					NSString *addressLine = [NSString stringWithFormat:@"%@\n%@",[person.details valueForKey:@"address"],[person.details valueForKey:@"citystatezip"]]; 
					cell.detailTextLabel.text = addressLine;
					cell.detailTextLabel.numberOfLines = 2;
					cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
					
					if( [cell.detailTextLabel.text length] > 0 ) {
						UIImageView *accImage = [[ UIImageView alloc ] 
												 initWithImage:[UIImage imageNamed:@"map.png" ]];
						cell.accessoryView = accImage;
						[accImage release];
					}
					break;
				case 1:
					cell.textLabel.text = @"Age";
					cell.detailTextLabel.text = [person.details valueForKey:@"age"];
					break;
				case 2:
					cell.textLabel.text = @"Birth Date";
					cell.detailTextLabel.text = [person.details valueForKey:@"birthdate"];
					break;
				
			}
			break;
		case 1:
						
			switch (indexPath.row) {
				
				case 0:
					cell.textLabel.text = @"Home Phone";
					cell.detailTextLabel.text = [person.details valueForKey:@"homephone"];
					if( [cell.detailTextLabel.text length] > 0 ) {
						UIImageView *accImage = [[ UIImageView alloc ] 
												 initWithImage:[UIImage imageNamed:@"phone.png" ]];
						cell.accessoryView = accImage;
						[accImage release];
					}
					break;
				case 1:
					cell.textLabel.text = @"Cell Phone";
					cell.detailTextLabel.text = [person.details valueForKey:@"cellphone"];
					if( [cell.detailTextLabel.text length] > 0 ) {
						UIImageView *accImage = [[ UIImageView alloc ] 
												 initWithImage:[UIImage imageNamed:@"phone.png" ]];
						cell.accessoryView = accImage;
						[accImage release];
					}
					break;
				case 2:
					cell.textLabel.text = @"Work Phone";
					cell.detailTextLabel.text = [person.details valueForKey:@"workphone"];
					if( [cell.detailTextLabel.text length] > 0 ) {
						UIImageView *accImage = [[ UIImageView alloc ] 
												 initWithImage:[UIImage imageNamed:@"phone.png" ]];
						cell.accessoryView = accImage;
						[accImage release];
					}
					break;
				case 3:
					cell.textLabel.text = @"Email";
					cell.detailTextLabel.text = [person.details valueForKey:@"email"];
					if( [cell.detailTextLabel.text length] > 0 ) {
						UIImageView *accImage = [[ UIImageView alloc ] 
												 initWithImage:[UIImage imageNamed:@"mail.png" ]];
						cell.accessoryView = accImage;
						[accImage release];
					}
					break;
			}
			
			if( [cell.detailTextLabel.text length] > 0 ) 
				cell.selectionStyle = UITableViewCellSelectionStyleNone;			
			
			break;			
			
	}
	
	if( indexPath.section >= 2 ) {
	   cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

	   if( indexPath.section == 2 && [person.familyMembers count] > 0 ) {
		   cell.textLabel.text = [[person.familyMembers objectAtIndex:indexPath.row] valueForKey:@"name"];
		   cell.detailTextLabel.text = [NSString stringWithFormat:@"Age: %@", [[person.familyMembers objectAtIndex:indexPath.row] valueForKey:@"age"] ];
	   } else { 
		   cell.textLabel.text = [[person.relatives objectAtIndex:indexPath.row] valueForKey:@"description"];
		   cell.textLabel.numberOfLines = 2;
		   cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;	
		   cell.detailTextLabel.text = @"";
	   }
	}
	   
	return cell;
}


-(void) downloadPhoto {
	[imageLoad startAnimating];
	
	BVCMSAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	
	NSLog(@"building query string");
	NSString *urlString = [NSString stringWithFormat:@"https://%@/iphone/FetchImage/%@", delegate.cmsServer, [person.details valueForKey:@"peopleid"] ];
	
	urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	NSLog(@"%@", urlString);
	NSURL *url = [NSURL URLWithString:urlString];
	
	HttpConnectionHandler *connectionHandler = [HttpConnectionHandler withURL:url andUsername:delegate.username andPassword:delegate.password];
	
	connectionHandler.errorCallback = @selector(photoDownload_error_callback:);
	connectionHandler.callback = @selector(photoDownload_callback:);
	connectionHandler.delegate = self;
	[connectionHandler processRequest];
}

/* 
 Selector called by successful image download.
 */
-(void) photoDownload_callback:(NSData *)data {
	[imageLoad stopAnimating];
	
	personImage = [[UIImage alloc] initWithData:data];
    [photo setImage:personImage];
	photo.contentMode = UIViewContentModeScaleAspectFill;
	
	isImageLoaded = YES;
}

/*
 Selector called by unsuccessful image download.
 */
-(void) photoDownload_error_callback:(NSError *)error {
	NSLog(@"Connection failed! Error - %@",
          [error localizedDescription]);
	
	[imageLoad stopAnimating];
	
}


- (void)update:(PersonDetails*)selectedPerson {
	self.person = selectedPerson;
	[table reloadData];
}


- (IBAction)photoButtonPressed:(id)sender
{
	NSLog(@"User clicked: viewPhotoButton");
	
	if( isImageLoaded ) {
		// Load search form
		ImageViewController	*imageView = [[ImageViewController alloc]
										  initWithNibName:@"ImageView" bundle:[NSBundle mainBundle]];
		
		imageView.title = @"Member Photo";
		imageView.photo = personImage;
		
		[self.navigationController pushViewController:imageView animated:YES];
		
		[imageView release];
	}
	
}



- (void)personDetailsCallback:(PersonDetails *)personDetails {
	NSLog(@"personDetailsCallback");
	SearchResultDetailViewController *searchResult = [[SearchResultDetailViewController alloc]
													  initWithNibName:@"SearchResultDetailView" bundle:[NSBundle mainBundle]];
	searchResult.title = @"Person Details";
	searchResult.person = personDetails;
	
	[self.view sendSubviewToBack:loadingView];
	[connection release];
	
	UINavigationController *navController = self.navigationController;
	[navController popToRootViewControllerAnimated:NO];
	[navController pushViewController:searchResult animated:YES];
	
	[searchResult release];
	
}

- (void)personDetailsFailed:(NSError *)error {
	[self.view sendSubviewToBack:loadingView];
	
	[connection release];
	
	UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:[error localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[connectionError show];
	[connectionError release];
}



/* 
 Release allocated memory.
 */
- (void)dealloc {
	[person release];
	[table release];
	[photo release];
	
	personImage = nil;
	[personImage release];
	
	[nameLabel release];
	[statusLabel release];
	[headerView release];
	[imageLoad release];
	
	connection = nil;
	[connection release];
    [super dealloc];
}




@end
